package com.hudson.broker.monitor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 记录相关生产者和消费者的速率
 */
public class BizMonitor {
    private static final Logger logger = LoggerFactory.getLogger(BizMonitor.class);

    // 记录消费速率
    public static AtomicInteger CONSUME_SPEED = new AtomicInteger(0);
    // 记录生产速率
    public static AtomicInteger PRODUCE_SPEED = new AtomicInteger(0);
    // 记录历史消费速率
    public static List<SpeedDomain> HISTORY_CONSUME_SPEED = new ArrayList<>();
    // 记录历史生产速率
    public static List<SpeedDomain> HISTORY_PRODUCE_SPEED = new ArrayList<>();
    private static final int RELAY_TIME = 10;
    private static final int MAX_SIZE = 10_000;

    static {
        ThreadPoolHelper.DEFAULT_SCHEDULED_POOL.scheduleAtFixedRateByWatch(() -> {
            int consume = CONSUME_SPEED.getAndSet(0);
            int produce = PRODUCE_SPEED.getAndSet(0);
            if (HISTORY_CONSUME_SPEED.size() >= MAX_SIZE) {
                HISTORY_CONSUME_SPEED = new ArrayList<>(HISTORY_CONSUME_SPEED.subList(MAX_SIZE / 2, HISTORY_CONSUME_SPEED.size()));
            }
            if (HISTORY_PRODUCE_SPEED.size() >= MAX_SIZE) {
                HISTORY_PRODUCE_SPEED = new ArrayList<>(HISTORY_PRODUCE_SPEED.subList(MAX_SIZE / 2, HISTORY_PRODUCE_SPEED.size()));
            }
            HISTORY_CONSUME_SPEED.add(new SpeedDomain(System.currentTimeMillis(), consume / 10));
            HISTORY_PRODUCE_SPEED.add(new SpeedDomain(System.currentTimeMillis(), produce / 10));
            logger.debug("生产者10s内吞吐量:{}", produce);
            logger.debug("消费者10s内吞吐量:{}", consume);
        }, RELAY_TIME, RELAY_TIME, TimeUnit.SECONDS);
    }

    public Map<String, List<SpeedDomain>> getBizSpeed() {
        return Map.of("consume", HISTORY_CONSUME_SPEED, "produce", HISTORY_PRODUCE_SPEED);
    }


    public record SpeedDomain(long recordTime, int speedTotal) {
    }
}


